<?php
class DownloadUrlAction extends BaseAction {
    protected $pushConroller;
    protected $config;

    public function __construct(){
        $this->pushConroller = A('admin://Push');
        $this->config = M('Config')->where("id=1")->limit(1)->select();
        // $this->pushConroller->test();exit;
    }

    public function index()
    {
        set_time_limit(0);
        $citys      = M('city')->field('id, pinyin')->where("pinyin <> ''")->select();
        $categorys  = M('category')->field('path, id')->select();
        $areas      = M('area')->field('id, pinyin, cityid')->where("pinyin <> ''")->select();

        if($this->config[0]['is_auto_spread_xzt'] == 1) {
            // 获取“当天”的文章链接 推送熊掌天接口
            $this->pushXzt($citys, $categorys, $areas);
        }

        $condition['push_status']  = array('in','0,2');

        $count      = M('zhaopin')->where($condition)->count();
//        $count = 100;
//        
        $this->pcUrl($citys, $areas, $categorys);
        $this->mipUrl($citys, $areas, $categorys);

        $pageSize = 1000;
        $pageNum = ceil($count / $pageSize);

        for ($i = 1; $i <=$pageNum; $i ++ )
        {
            $zhaopins = M('zhaopin')->where($condition)->field('id, cityid, areaid, cid')->limit((($i - 1) * $pageSize), $pageSize)->order('id asc')->select();
            $this->zhaopinUrl('pc', $citys, $areas, $categorys, $zhaopins, $i);
            $this->zhaopinUrl('mip', $citys, $areas, $categorys, $zhaopins, $i);
            // 推送后修改文章记录推送状态
            $this->updateForPushArticle($zhaopins);
        }
    }

    public function pushXzt($citys, $categorys, $areas){
        // 当天时间
        $startTime = strtotime(date('Y-m-d 00:00:00'));
        $endTime = strtotime(date('Y-m-d 23:59:59'));

        $condition['createtime'] =  array('BETWEEN', array($startTime,$endTime));
        $condition['push_status']  = array('in','0,2');

        $count      = M('zhaopin')->where($condition)->count();

        $pageSize = 1000;
        $pageNum = ceil($count / $pageSize);

        for ($i = 1; $i <=$pageNum; $i ++ )
        {
            $zhaopins = M('zhaopin')->where($condition)->field('id, cityid, areaid, cid')->limit((($i - 1) * $pageSize), $pageSize)->order('id asc')->select();
            $this->zhaopinUrlXzt('pc', $citys, $areas, $categorys, $zhaopins, $i);
            $this->zhaopinUrlXzt('mip', $citys, $areas, $categorys, $zhaopins, $i);
        }
        
    }

    public function updateForPushArticle($zhaopins){
        $articleIds = array();
        foreach($zhaopins as $article){
            $articleIds[] = $article['id'];
        }

        $where['id'] = array('in', $articleIds);

        $data['push_time'] = time();
        $data['push_status'] = 1;   
        $ret = M('zhaopin')->where($where)->save($data);
        return $ret;
    }

    // 推送每次限制2000条
    function pcUrl($citys, $areas, $categorys, $i = 0)
    {
        $citys = array_column($citys, 'pinyin', 'id');
        $categorys = array_column($categorys, 'path', 'id');

        $cityUrl = $this->getPcCityUrl($citys);
        $this->saveFile('city', 'pc_'.$i, $cityUrl);
        // $this->pushConroller->pushApiForPc($cityUrl);

        $categoryUrl = $this->getPcCityCateUrl($citys, $categorys);
        $this->saveFile('category', 'pc_city_'.$i, $categoryUrl);
        // $this->pushConroller->pushApiForPc($categoryUrl);

        $areaUrl = $this->getPcAreaCityUrl($citys, $areas);
        $this->saveFile('area', 'pc_'.$i, $areaUrl);
        // $this->pushConroller->pushApiForPc($areaUrl);

        $areaCate = $this->getPcCityAreaCateUrl($categorys, $citys, $areas);
        $this->saveFile('category', 'pc_area_'.$i, $areaCate);
        // $this->pushConroller->pushApiForPc($areaCate);
    }

    function zhaopinUrl($type, $citys, $areas, $categorys, $zhaopins, $i = 0)
    {
        $citys = array_column($citys, 'pinyin', 'id');
        $categorys = array_column($categorys, 'path', 'id');
        if ($type == 'pc')
        {
            $zhaopin =  $this->getPcCityZhaopinUrl($citys, $areas, $categorys, $zhaopins);
            // $this->saveFile('zhaopin', 'pc_'.$i, $zhaopin);
            $this->pushConroller->pushApiForPc($zhaopin);

//            $zhaopin =  $this->getPcCityAreaZhaopinUrl($citys, $areas, $categorys, $zhaopins);
            // $this->saveFile('zhaopin', 'pc_area_'.$i, $zhaopin);
//            $this->pushConroller->pushApiForPc($zhaopin);
        } elseif($type == 'mip') {
            $mipZhaopin = $this->getMipCityZhaopinUrl($citys, $areas, $categorys, $zhaopins);
            // $this->saveFile('zhaopin', 'mip_'.$i, $mipZhaopin);
            $this->pushConroller->pushApiForMip($mipZhaopin);
        }
    }

    function zhaopinUrlXzt($type, $citys, $areas, $categorys, $zhaopins, $i = 0)
    {
        $citys = array_column($citys, 'pinyin', 'id');
        $categorys = array_column($categorys, 'path', 'id');
        if ($type == 'pc')
        {
            $zhaopin =  $this->getPcCityZhaopinUrl($citys, $areas, $categorys, $zhaopins);
            // $this->saveFile('zhaopin', 'pc_'.$i, $zhaopin);
            $this->pushConroller->baiduPushForXzt($zhaopin);            
        } elseif($type == 'mip') {
            $mipZhaopin = $this->getMipCityZhaopinUrl($citys, $areas, $categorys, $zhaopins);
            // $this->saveFile('zhaopin', 'mip_'.$i, $mipZhaopin);
            $this->pushConroller->baiduPushForXzt($mipZhaopin);
        }
    }

    function mipUrl($citys, $areas, $categorys, $i = 0)
    {
        $citys = array_column($citys, 'pinyin', 'id');
        $categorys = array_column($categorys, 'path', 'id');

        $mipCity = $this->getMipCityUrl($citys);
        // $this->saveFile('city', 'mip_'.$i, $mipCity);
        $this->pushConroller->pushApiForMip($mipCity);

        $mipCityCategory = $this->getMipCityCateUrl($citys, $categorys);
        // $this->saveFile('category', 'mip_city_'.$i, $mipCityCategory);
        $this->pushConroller->pushApiForMip($mipCityCategory);

        $mipCityAreaCateCity = $this->getMipCityAreaCateUrl($categorys, $citys, $areas);
        // $this->saveFile('category', 'mip_area_'.$i, $mipCityAreaCateCity);
        $this->pushConroller->pushApiForMip($mipCityAreaCateCity);

        $areaUrl = $this->getMipAreaCityUrl($citys, $areas);
        // $this->saveFile('area', 'mip_'.$i, $areaUrl);
        $this->pushConroller->pushApiForMip($areaUrl);
    }

    function saveFile($dir, $filename, $data)
    {
        array_filter($data);
        if (empty($data))
        {
            return false;
        }
        $dir = './Url/'.$dir;
        if (!is_dir($dir))
        {
            mkdir($dir, 0777);
        }
        $file = fopen($dir."/".$filename.".txt", "w");
        fwrite($file, implode("\r\n", $data));
        fclose($file);
    }

    function getPcCityUrl($citys, $http = "https", $domain = 'yeczj', $dot = "com")
    {
        if (is_array($citys))
        {
            $url = array();
            foreach ($citys as $city)
            {
                $url[] = $this->getPcCityUrl($city, $http, $domain, $dot);
            }
        } else {
            return "{$http}://{$domain}.{$dot}/{$citys}/";
        }
        return $url;
    }
    function getPcAreaCityUrl($citys, $areas, $http = "https", $domain = 'yeczj', $dot = "com")
    {
        $url = array();
        foreach ($areas as $area)
        {
            if (isset($citys[$area['cityid']]))
            {
                $city   = $this->getPcCityUrl($citys[$area['cityid']], $http, $domain , $dot );
                $url[]  = $city.$area['pinyin'];
            }
        }
        return $url;
    }

    function getPcCityCateUrl($citys, $categorys)
    {
        $url = array();
        foreach ($citys as $city)
        {
            foreach ($categorys as $category)
            {
                $url[] = $this->getPcCityUrl($city)."{$category}/";
            }
        }
        return $url;
    }

    function getPcCityAreaCateUrl($categorys, $citys, $areas)
    {
        $url = array();
        foreach ($areas as $area)
        {
            if (isset($citys[$area['cityid']]))
            {
                foreach ($categorys as $category)
                {

                    $url[] = $this->getPcCityUrl($citys[$area['cityid']])."{$area['pinyin']}/{$category}/";
                }
            }
        }
        return $url;
    }

    function getPcCityZhaopinUrl($citys, $areas, $categorys, $zhaopins)
    {
        // xx.ab.com/地区/分类/id.html
        //xx.ab.com/分类/id.html
        $url = array();
        foreach ($zhaopins as $zhaopin)
        {   
            if (!isset($categorys[$zhaopin['cid']]))
            {
                continue;
            }
            //城市
            if (!empty($zhaopin['cityid'])
                && isset($citys[$zhaopin['cityid']])
            )
            {
                $domain = $this->getPcCityUrl($citys[$zhaopin['cityid']]);
                $url[$zhaopin['id']] = "{$domain}{$categorys[$zhaopin['cid']]}/{$zhaopin['id']}.html";
            }
        }
        return $url;
    }

//    function getPcCityAreaZhaopinUrl($citys, $areas, $categorys, $zhaopins)
//    {
//        // xx.ab.com/地区/分类/id.html
//        //xx.ab.com/分类/id.html
//        $url = array();
//        $areas = array_column($areas, 'pinyin', 'id');
//        foreach ($zhaopins as $zhaopin)
//        {
//            if (!isset($categorys[$zhaopin['cid']]))
//            {
//                continue;
//            }
//            //城市地区
//            if (!empty($zhaopin['cityid'])
//                && isset($citys[$zhaopin['cityid']])
//                && isset($areas[$zhaopin['areaid']])
//            )
//            {
//                $domain = $this->getPcCityUrl($citys[$zhaopin['cityid']]);
//                $url[$zhaopin['id']] = "{$domain}{$areas[$zhaopin['areaid']]}/{$categorys[$zhaopin['cid']]}/{$zhaopin['id']}.html";
//            }
//        }
//        return $url;
//    }


    function getMipCityUrl($citys, $http = "https", $pre = 'mip.', $domain = 'yeczj', $dot = "com")
    {
        if (is_array($citys))
        {
            $url = array();
            foreach ($citys as $city)
            {
                $url[] = $this->getMipCityUrl($city, $http, $pre, $domain, $dot);
            }
        } else {
            return "{$http}://{$pre}{$domain}.{$dot}/{$citys}/";
        }
        return $url;
    }

    function getMipAreaCityUrl($citys, $areas, $http = "https", $domain = 'yeczj', $dot = "com")
    {
        $url = array();
        foreach ($areas as $area)
        {
            if (isset($citys[$area['cityid']]))
            {
                $city   = $this->getMipCityUrl($citys[$area['cityid']], $http, $domain , $dot );
                $url[]  = $city.$area['pinyin'];
            }
        }
        return $url;
    }

    function getMipCityCateUrl($citys, $categorys)
    {
        $url = array();
        foreach ($citys as $city)
        {
            foreach ($categorys as $category)
            {
                $url[] = $this->getMipCityUrl($city)."{$category}/";
            }
        }
        return $url;
    }


    function getMipCityAreaCateUrl($categorys, $citys, $areas)
    {

        $url = array();
        foreach ($citys as $cityid => $city)
        {
            foreach ($areas as $area)
            {
                if ($cityid == $area['cityid'])
                {
                    foreach ($categorys as $category)
                    {

                        $url[] = $this->getMipCityUrl($city)."{$category}/?areaid={$area['id']}";
                    }
                }
            }
        }
        return $url;
    }



    function getMipCityZhaopinUrl($citys, $areas, $categorys, $zhaopins)
    {
        // xx.ab.com/地区/分类/id.html
        //xx.ab.com/分类/id.html
        $url = array();
        foreach ($zhaopins as $zhaopin)
        {
            if (!isset($categorys[$zhaopin['cid']]))
            {
                continue;
            }
            //城市
            if (empty($zhaopin['areaid'])
                && !empty($zhaopin['cityid'])
                && isset($citys[$zhaopin['cityid']])
            )
            {
                $domain = $this->getMipCityUrl($citys[$zhaopin['cityid']]);
                $url[$zhaopin['id']] = "{$domain}{$categorys[$zhaopin['cid']]}/{$zhaopin['id']}.html";
            }
        }

        return $url;
    }
}

if (!function_exists('array_column'))
{
    function array_column($arr, $field, $key = '')
    {
        $data = array();
        foreach ($arr as $value)
        {
            if (empty($key))
                $data[] = $value[$field];
            else
                $data[$value[$key]] = $value[$field];
        }
        return $data;
    }
}
